package tutor;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Screen;
import javax.microedition.lcdui.TextField;

/**
 *
 * @author y_plaksyuk
 */
public class ArithmeticUnit extends AbstractUnit {

	private final ArithmeticQuestion question;

	private Form form;
	private TextField item;
	private int answer;
	private long startTime;

	public ArithmeticUnit(TutorApp app, ArithmeticQuestion question) {
		super(app);

		this.question = question;
	}

	public String getTitle() {
		return question.getTitle();
	}

	public Screen getScreen() {
		if (form == null) {
			form = new Form("Arithmetic");
			form.addCommand(app.getNextCommand());
			form.addCommand(app.getCancelCommand());
		}

		return form;
	}

	public void start() {
		if (form != null)
			form.deleteAll();

		super.start();

		startTime = System.currentTimeMillis();
		insertQuestion();
	}

	protected void insertQuertsion(int v1, int v2, int res) {
		item = new TextField(v1 + " " + question.getTitle() + " " + v2 + " = ?", null, 3, TextField.NUMERIC);
		item.setLayout(TextField.LAYOUT_NEWLINE_AFTER | TextField.LAYOUT_EXPAND);

		form.append(item);
		app.getDisplay().setCurrentItem(item);

		answer = res;
	}

	public void insertQuestion() {
		question.askQuestion(this);
	}

	protected void handleCommand(Command command) {
		if (command == app.getNextCommand()) {
			String value = item.getString();
			if (value != null && value.length() > 0) {
				if (Integer.parseInt(value) == answer) {
					item.setConstraints(TextField.UNEDITABLE);

					if (form.size() < 10)
						insertQuestion();
					else
						app.switchDisplayable(getResultAlert(), app.getMainScreen());
				}
				else
					beep();
			}
		}
		else
			super.handleCommand(command);
	}

	private Alert getResultAlert() {
		String text = ((System.currentTimeMillis() - startTime) / 1000) + " sec";
		return new Alert("Result", text, null, AlertType.INFO);
	}

	private void beep() {
		app.getDisplay().vibrate(500);
	}
}
